package resource

import (
	"net/http"

	"github.com/go-playground/validator/v10"
	"github.com/infraboard/mcube/http/request"
)

const (
	AppName = "resource"
)

var (
	validate = validator.New()
)

type Service interface {
	RPCServer
}

func (m *Meta) TableName() string {
	return "resource_meta"
}

func (r *Resource) Validate() error {
	validateStructs := []any{r.Meta, r.Spec, r.Cost}
	for _, v := range validateStructs {
		err := validate.Struct(v)
		if err != nil {
			return err
		}
	}

	return nil
}

func NewQueryResourceRequest() *QueryResourceRequest {
	return &QueryResourceRequest{
		Page: request.NewDefaultPageRequest(),
	}
}

func NewDefaultResource(rt TYPE) *Resource {
	return &Resource{
		Meta: &Meta{},
		Spec: &Spec{
			ResourceType: rt,
		},
		Cost:   &Cost{},
		Status: &Status{},
		Tags:   []*Tag{},
	}
}

func NewResourceSet() *ResourceSet {
	return &ResourceSet{
		Items: []*Resource{},
	}
}

func (s *ResourceSet) Add(item *Resource) {
	s.Items = append(s.Items, item)
}

func NewQueryResourceRequestFromHTTP(r *http.Request) *QueryResourceRequest {
	req := NewQueryResourceRequest()
	qs := r.URL.Query()
	req.Domain = qs.Get("domain")
	req.Namespace = qs.Get("namespace")
	req.Env = qs.Get("env")
	req.Keywords = qs.Get("keywords")
	req.Page = request.NewPageRequestFromHTTP(r)
	return req
}

func NewGroupTag(key, value string) *Tag {
	return &Tag{
		Purpose: TAG_PURPOSE_GROUP,
		Key:     key,
		Value:   value,
		Weight:  1,
	}
}
